const center = require('unmp-center');
const dgram = require('dgram');

const myid = new Uint8Array([0x84, 0x12, 0x01, 0x02, 0x05]);
const private_key = new Uint8Array([202, 239, 123, 108, 182, 66, 137, 226]);
const public_key = new Uint8Array([79, 171, 204, 102, 2, 80, 179, 247]);
const product_id = BigInt(258);
const product_key = new Uint8Array([0xc8, 0x33, 0x97, 0x7a, 0x7b, 0x16, 0x0b, 0xac]);

const udp_client = dgram.createSocket('udp4');
udp_client.on('close', function () {
  console.log('udp client closed.');
});
udp_client.on('error', function () {
  console.log('udp client error.');
});
udp_client.on('message', function (msg, rinfo) {
  //console.log(`receive message from ${rinfo.address}:${rinfo.port}：${msg}`);
  center.recv(msg);
});

center.init(
  myid,
  (buf) => {
    udp_client.send(buf, 0, buf.length, 16464, 'iot.crise.cn');
  },
  3,
);
setInterval(() => {
  center.tick(100);
}, 100);
center.on_getid((id, private_key, public_key) => {
  console.log('getid:', id, private_key, public_key);
});
center.on_login(() => {
  console.log('login.');
  center.set_actual(myid, public_key, 0x8001, new Uint8Array([0x03]));
  setInterval(() => {
    center.heart();
  }, 30000);
});
center.on_change_actual((id, k, v) => {
  console.log('chg actual:', id, k, v);
});
center.on_change_target((id, k, v) => {
  console.log('chg target:', id, k, v);
});

center.login(myid, private_key);
